<template>
  <div :class="className" :style="{height:height,width:width}">
    <e-host-list ref="hostList" :dialog="false" title="主机列表" />
  </div>
</template>

<script>
import echarts from 'echarts'
import '../../../../node_modules/echarts/map/js/world.js'
import axios from 'axios'
import request from '@/utils/request'
// import { constants } from 'crypto'
import eHostList from './hostList'
require('echarts/theme/macarons') // echarts theme

var defaultP = [
  [{
    name: 'China',
    value: 300,
    selected: true
  }]
]
var chinaId = 100000

export default {
  components: { eHostList },
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '490px'
    },
    supThis: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      cityName: '中国',
      curGeoJson: null,
      curCityCode: null,
      curName: null,
      echartsMap: null,
      cityCode: 100000,
      chinaJson: null,
      vdata: [],
      levelColorMap: {
        '1': 'rgba(241, 109, 115, .8)',
        '2': 'rgba(255, 235, 59, .7)',
        '3': 'rgba(147, 235, 248, 1)'
      },
      alarmData: [],
      fullImage: null,
      groupid: ''
    }
  },
  beforeDestroy() {
    if (!this.echartsMap) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.echartsMap.dispose()
    this.echartsMap = null
  },
  mounted() {
    // this.supThis.$refs.elCard.$el.children[1].style.padding = '0px'; TODO
    this.echartsMap = echarts.init(this.$el, 'macarons')
    this.echartsMap.on('click', this.echartsMapClick)
    this.echartsMap.on('georoam', function(params) {})
    var img = new Image()
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    canvas.width = this.echartsMap.getWidth() * window.devicePixelRatio
    canvas.height = this.echartsMap.getHeight() * window.devicePixelRatio
    this.fullImage = new Image()
    img.src = ''
    var fullImage = this.fullImage
    var echartsMap = this.echartsMap
    img.onload = function() {
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      fullImage.src = canvas.toDataURL()
      setTimeout(function() {
        echartsMap.resize()
      }, 100)
    }
    this.loadMap('world')
  },
  methods: {
    echartsMapClick(params) { // 地图点击事件
      console.log('echartsMapClick', params)
      var id = this.cityCode
      if (params.name === 'China') {
        // this.getData(this.cityCode)
        id = chinaId
        this.changeBreadcrumb(id, params.name)
      } else {
        id = this.getMapId(this.curGeoJson, params.name)
        if (id) {
          /*
          if(String(id).substr(2)=="0000") {
            this.changeBreadcrumb(id,params.name)
            //this.getData(id)
          } */
          this.changeBreadcrumb(id, params.name)
          if (id !== this.cityCode) {
            this.cityCode = id
          }
        } else {
          this.loadMap('world')
          this.cityCode = chinaId
        }
      }
    },
    changeBreadcrumb(id, name) {
      var j = this.supThis.levelList.length
      console.log(id, name, this.cityCode)
      if (!id) {
        this.supThis.levelList = this.supThis.levelList.slice(0, 1)
        this.loadMap('world')
        this.cityCode = null
      } else {
        // console.log('begin getData')
        this.getData(id)
        if (name === '中国' || name === 'China') {
          this.supThis.levelList = this.supThis.levelList.slice(0, 1)
          this.supThis.levelList.push({ path: '', id: id, title: '中国' })
        } else {
          if (id % 10000 === 0) {
            if (j >= 3) {
              this.supThis.levelList = this.supThis.levelList.slice(0, 2)
            }
          } else {
            if (j > 3) {
              this.supThis.levelList = this.supThis.levelList.slice(0, 3)
            }
          }
          this.supThis.levelList.push({ path: '', id: id, title: name })
        }
      }
    },
    loadMapData(areaCode) {
      axios.get('/json/map/' + areaCode + '.json').then(response => {
        const mapJson = response.data
        this.curGeoJson = mapJson
        this.curCityCode = areaCode
        this.loadMap(this.cityName, mapJson)
      })
    },
    loadMap(mapName, mapData) {
      console.log('loadMap', mapData)
      var option = {}
      if (mapData) {
        // var that = this
        this.echartsMap.clear()
        echarts.registerMap(mapName, mapData)
        option = {
          backgroundColor: {
            image: this.fullImage
          },
          geo: {
            show: true,
            zoom: 1.2,
            map: mapName,
            geoIndex: 0,
            roam: true,
            label: {
              normal: {
                show: false
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                areaColor: '#031525',
                borderColor: '#3B5077',
                borderWidth: 1
              },
              emphasis: {
                areaColor: '#17538a'
              }
            }
          },
          series: [{
            type: 'map',
            map: mapName === 'China' ? 'china' : mapName,
            zoom: 1.2,
            geoIndex: 0,
            data: this.initSeriesDataEx(this.vdata),
            label: {
              normal: { show: false },
              emphasis: {
                show: false,
                textStyle: {
                  color: '#fff'
                }
              }
            },
            itemStyle: {
              normal: {
                areaColor: '#031525',
                borderColor: '#3B5077',
                borderWidth: 1
              },
              emphasis: {
                areaColor: '#17538a'
              }
            }
          },
          {
            type: 'effectScatter',
            map: mapName === 'China' ? 'china' : mapName,
            coordinateSystem: 'geo',
            symbolSize: 6,
            data: this.initSeriesData(this.vdata),
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke',
              period: 2
            },
            hoverAnimation: true,
            /* label: {
              normal: {
                formatter: '{b}',
                position: 'top',
                show: true,
              }
            }, */
            itemStyle: {
              normal: {
                color: function(params) {
                  if (params.value[2] >= 4) {
                    return '#CD0000'
                  } else if (params.value[2] === 0) {
                    return '#00FF00'
                  } else if (params.value[2] === 1) {
                    return '#ADFF2F'
                  } else {
                    return '#f4e83d'
                  }
                },
                shadowBlur: 10,
                shadowColor: '#333'
              }
            }
            // zlevel: 6
          }]
        } // end of option
        this.echartsMap.setOption(option)
      } else {
        this.echartsMap.clear()
        option = {
          backgroundColor: {
            image: this.fullImage
          },
          geo: {
            show: true,
            zoom: 1.2,
            map: mapName,
            label: {
              normal: {
                show: false,
                textStyle: {
                  color: '#fff'
                }
              },
              emphasis: {
                textStyle: {
                  color: '#fff'
                }
              }
            },
            regions: defaultP[0],
            roam: false,
            itemStyle: {
              normal: {
                areaColor: '#d7e9f6',
                borderColor: '#3B5077'
              },
              emphasis: {
                areaColor: '#2B91B7'
              }
            }
          },
          series: [{
            type: 'map',
            roam: false,
            data: [
              { name: 'China', value: 28397.812 }
            ],
            itemStyle: {
              normal: {
                color: function(params) {
                  if (params.name === 'China') {
                    return '#2B91B7' // 'rgba(241, 109, 115, .8)'
                  }
                },
                areaColor: '#031525',
                borderColor: '#3B5077',
                borderWidth: 1,
                label: {
                  show: false,
                  textStyle: {
                    color: 'rgb(249, 249, 249)'
                  }
                }
              },
              emphasis: {
                areaColor: '#2B91B7',
                borderColor: '#fff',
                areaStyle: {
                  color: '#2B91B7'
                },
                label: {
                  show: false,
                  textStyle: {
                    color: 'rgb(249, 249, 249)'
                  }
                }
              }
            }
          }]
        } // end of option
        this.echartsMap.setOption(option)
      }
    },
    getData(adcode) {
      const params = {
        parentCityCode: adcode === 100000 ? '' : adcode
      }
      request({
        url: 'web/zabbix/alarms/get',
        method: 'get',
        params
      }).then(res => {
        this.vdata = [].concat(res)
        if (adcode % 10000 === 0 &&
          (adcode !== 110000 && adcode !== 500000 && adcode !== 310000 && adcode !== 120000 &&
          adcode !== 810000 && adcode !== 820000 && adcode !== 710000)) {
          this.loadMapData(adcode)
        } else {
          // this.supThis.getAlarmHost(adcode,'')
          this.getAlarmHost(adcode, this.groupid)
          this.$refs.hostList.dialog = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getMapId(mapJson, name) {
      for (var i = 0; i < mapJson.features.length; i++) {
        if (name === mapJson.features[i].properties.name) {
          return mapJson.features[i].id
        }
      }
    },
    generateJson(v, alarmCount) {
      var obj = {}
      obj.name = v.properties.name
      if (alarmCount) {
        obj.value = v.properties.cp.concat(alarmCount, 0)
      } else {
        obj.value = v.properties.cp.concat(0, 0)
      }
      var label = { formatter: '{b}', show: true, position: 'top', distance: 5 }
      obj.label = label
      if (v.properties.name === '澳门') {
        obj.label.position = 'bottom'
      }
      if (v.properties.name === '香港' || v.properties.name === '上海' || v.properties.name === '天津' ||
        v.properties.name === '浙江' || v.properties.name === '江苏') {
        obj.label.position = 'right'
      }
      var nameStr = v.properties.name
      if (v.properties.name === '山西') {
        obj.label.position = 'left'
      } else if (nameStr === '北屯市' || nameStr === '可克达拉市' || nameStr === '喀什地区' || nameStr === '和田地区' || nameStr === '巴音郭楞蒙古自治州' ||
        nameStr === '图木舒克市' || nameStr === '乌鲁木齐市' || nameStr === '吐鲁番市' || nameStr === '五家渠市' ||
        nameStr === '双河市' || nameStr === '乌兰察布市' || nameStr === '海东市' || nameStr === '双鸭山市' ||
        nameStr === '鸡西市' || nameStr === '酒泉市' || nameStr === '定西市' || nameStr === '资阳市' ||
        nameStr === '内江市' || nameStr === '自贡市' || nameStr === '泸州市' ||
        nameStr === '昆明市' || nameStr === '鄂州市' || nameStr === '镇江市' || nameStr === '琼中黎族苗族自治县' ||
        nameStr === '陵水黎族自治县' || nameStr === '五指山市' || nameStr === '保亭黎族苗族自治县'
      ) {
        obj.label.position = 'right'
      } else if (
        nameStr === '昌吉回族自治州' || nameStr === '咸阳市' || nameStr === '揭阳市' || nameStr === '江门市' || nameStr === '云浮市'
      ) {
        obj.label.position = 'left'
      } else if (nameStr === '包头市' ||
        nameStr === '鄂尔多斯市' || nameStr === '晋中市' || nameStr === '雅安市' || nameStr === '乐山市' ||
        nameStr === '文山壮族苗族自治州' || nameStr === '白沙黎族自治县' || nameStr === '佛山市' ||
        nameStr === '中山市' || nameStr === '珠海市' || nameStr === '东莞市' || nameStr === '深圳市' ||
        nameStr === '漳州市' || nameStr === '新余市' || nameStr === '株洲市' || nameStr === '黄石市'
      ) {
        obj.label.position = 'bottom'
      }
      return obj
    },

    initSeriesData(data) {
      var dataMap = {}
      var temp = []
      var mapFeatures = this.curGeoJson.features
      for (var i = 0; i < data.length; i++) {
        var id = data[i].cityCode
        dataMap[id] = data[i].alarmCount
      }
      var generateJson = this.generateJson
      mapFeatures.forEach(function(v) {
        if (v.properties.cp) {
          var id = v.id
          var alarmCount = dataMap[id]
          temp.push(generateJson(v, alarmCount))
        }
      })
      // console.log(temp)
      // for (var i = 0;i < data.length;i++) {
      //   var geoCoord = geoCoordMap[data[i].cityCode]
      //   if(geoCoord) {
      //     temp.push({
      //       name: geoCoord.name,
      //       value: geoCoord.cp.concat(data[i].alarmCount, data[i].level)
      //     })
      //   }
      // }
      return temp
    },
    initSeriesDataEx(data) {
      var dataMap = {}
      var temp = []
      var mapFeatures = this.curGeoJson.features
      for (var i = 0; i < data.length; i++) {
        var id = data[i].cityCode
        dataMap[id] = data[i].alarmCount
      }
      // console.log(mapFeatures)
      mapFeatures.forEach(function(v) {
        if (v.properties.cp) {
          var id = v.id
          var alarmCount = dataMap[id]
          if (alarmCount) {
            temp.push({
              name: v.properties.name,
              value: v.properties.cp.concat(alarmCount, 0)
            })
          } else {
            temp.push({
              name: v.properties.name,
              value: v.properties.cp.concat(0, 0)
            })
          }
        }
      })
      return temp
    },
    getAlarmHost(cityCode, groupids) {
      const params = {
        cityCode: cityCode,
        groupids: groupids
      }
      request({
        url: 'web/zabbix/alarms/host',
        method: 'get',
        params
      }).then(res => {
        this.alarmData = [].concat(res)
        this.$refs.hostList.alarmData = this.alarmData.slice(0, 10)
        this.$refs.hostList.storeData = this.alarmData
        this.$refs.hostList.total = this.alarmData.length
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
